package cz.proks.bank.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cz.proks.bank.dao.BankDao;
import cz.proks.bank.domain.Bank;

@Repository
@Transactional
@Scope("prototype")
public class BankDaoImpl extends BaseGenericDaoImpl<Bank, String> implements BankDao {
	private final Logger log = Logger.getLogger(getClass());
	
	@PersistenceContext
	private EntityManager entityManager;
	
	public BankDaoImpl() {
		super(Bank.class);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public Bank getByCode(String bankCode) {
		log.debug("getByCode():: Start with bank code '" + bankCode + "'");
		
		Query query = entityManager.createNamedQuery("Bank.getByCode");
		query.setParameter("bankCode", bankCode);
		List<Bank> banks = query.getResultList();		
	
		Bank bank = banks != null && !banks.isEmpty() ? banks.get(0) : null;
		
		log.debug("getByCode():: Exit with bank '" + bank + "'");
		return bank;
	}



	@Override
	public Bank create(Bank entity) {	
		log.debug("save():: Saving entity '" + entity + "'");
		
		entityManager.persist(entity);		
		
		log.debug("save():: Exit with entity '" + entity + "'");
		return entity;
	}		
}
